
import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import router from '@/router';
import Qs from 'qs';
import { useUsertore } from '@/stores/user'//使用状态
import { ElMessage } from 'element-plus';
import cookie from 'js-cookie'
import Nprogress from 'nprogress';//引入加载进度条的样式

let baseURL = ''
/**development开发环境 production 生成环境（打包后） */
if (process.env.NODE_ENV === 'development') {
    baseURL = '/m.api'
} else {
    baseURL = 'http://zxwyit.cn:8989/m.api'
}

/**instance.get和instance.post返回的类型是AxiosResponse，
 但实际接口需要多一些字段（lierrno，errmsg），所有用extends继承 */
declare interface TypeResponse extends AxiosResponse {
    url(url: any): unknown;
    /**
     * 错误号，200成功，10006令牌过期
     */
    errno: number,
    errmsg: string
}

const instance: AxiosInstance = axios.create({
    baseURL,
    timeout: 5000,
    headers: { 'content-type': 'application/x-www-form-urlencoded' }
});

/** 添加请求拦截器 */
instance.interceptors.request.use((config: AxiosRequestConfig): AxiosRequestConfig => {// 在发送请求之前做些什么
    /**统一headers头 */
    if (config.headers) {
        config.headers['AdminToken '] = cookie.get('token')
        Nprogress.start()//开启进度条
    }
    return config;
}, (error) => {// 对请求错误做些什么
    console.log('请求错误')
    return Promise.reject(error);
});
const METHOD_TYPE = ['_mt=create', '_mt=edit', '_mt=delete', "_mt=update"]
const PARAM_TYPE = ['create', 'edit', 'delete', 'update']
/**添加响应拦截器 */
instance.interceptors.response.use(async (response: AxiosResponse) => {
    // 对响应数据做点什么
    console.log('进来了', response);
    const res = response.data
    let { errmsg, errno } = res
    let path = router.currentRoute.value.fullPath
    if (10006 === errno) {/**token过期 */
        //获取接口请求数据
        let configData = ''
        let index = 0
        if (response.config.data) {
            configData = response.config.data
            index = METHOD_TYPE.findIndex((item: any) => configData.includes(item))
        } else {
            configData = response.config.params._mt
            index = PARAM_TYPE.findIndex((item: any) => configData.includes(item))
        }
        //index判断是否进行无痛刷新 index不等于-1则需要无痛刷新令牌
        if (index === -1) {//index==-1需要重新获取令牌
            ElMessage.error(errmsg)
            router.replace({ path: "/login", query: { back: path } })//登录后需要跳回的地址
            return;
        } else {//否则无痛刷新令牌
            const store = useUsertore()
            const { username, password } = store.loginInfo;
            //重新获取令牌
            let loginData = { _gp: "admin", _mt: "login", username: username, password };
            console.log(username, password, '密码');

            const { errno, errmsg, data } = await post(loginData)//await方法同步获取请求
            if (200 == errno) {
                cookie.set("token", data)//保存令牌
            } else {
                router.replace({ path: "/login", query: { back: path } })//登录后需要跳回的地址
                return Promise.reject({ errno, errmsg, data })
            }
            //重新发送上次请求
            return instance.request(response.config)
        }
    }
    Nprogress.done()//结束进度条
    return res
}, (error) => {// 对响应错误做点什么
    console.error('请求响应错误', error)
    return Promise.reject(error);
});

export const get = (params?: object): Promise<TypeResponse> => {
    return instance.get('', { params })
}
export const post = (data: object, params?: object): Promise<TypeResponse> =>
    instance.post('', Qs.stringify(data), { params })
export function upload(data: object): Promise<TypeResponse> {
    return instance.post("../upload/admin", data);
}





